/*
 * Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
 * See LICENSE in the project root for license information.
 */

// images references in the manifest
import "../../assets/icon-16.png";
import "../../assets/icon-32.png";
import "../../assets/icon-80.png";

/* global document, Office, Word */

Office.onReady((info) => {
  if (info.host === Office.HostType.Word) {
    if (!Office.context.requirements.isSetSupported('WordApi', '1.3')) {
      console.log('Sorry. The tutorial add-in uses Word.js APIs that are not available in your version of Office.');
    }
    document.getElementById("check-context").onclick = checkContext;
    document.getElementById("sideload-msg").style.display = "none";
    document.getElementById("app-body").style.display = "flex";
  }
});


function checkLine(line) {
  let cnt = 0;
  for (let i = 0; i < line.length; i++) {
    if (line[i] == "的") {
      cnt++;
    }
    if (cnt >= 3) return true;
  }
  return false;
}

function colorText(line) {
  Word.run(function (context) {

    var searchResults = context.document.body.search(line, { ignorePunct: true });

    context.load(searchResults, 'font');

    return context.sync().then(function () {
      console.log('Found count: ' + searchResults.items.length);

      for (var i = 0; i < searchResults.items.length; i++) {
        searchResults.items[i].font.color = 'purple';
        searchResults.items[i].font.highlightColor = '#FFFF00'; //Yellow
        searchResults.items[i].font.bold = true;
      }

      return context.sync();
    });
  })
    .catch(function (error) {
      console.log('Error: ' + JSON.stringify(error));
      if (error instanceof OfficeExtension.Error) {
        console.log('Debug info: ' + JSON.stringify(error.debugInfo));
      }
    });
}

function checkContext() {
  Word.run(function (context) {
    var docBody = context.document.body;
    context.load(docBody, 'text');
    return context.sync().then(function () {
      var rg = /[,.，。\r]/;
      var documentTextArray = docBody.text.split(rg);
      for (let i = 0; i < documentTextArray.length; i++) {
        if (checkLine(documentTextArray[i])) {
          colorText(documentTextArray[i]);
        }
      }

    });

  }).catch(function (error) {
    console.log("Error: " + error);
    if (error instanceof OfficeExtension.Error) {
      console.log("Debug info: " + JSON.stringify(error.debugInfo));
    }
  });
}



